package qc.module.duty.api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import qc.common.core.constants.QCAuthConstant;
import qc.module.duty.dto.group.DutyGroupDto;
import qc.module.duty.service.DutyGroupService;
import qc.module.platform.dto.dept.DeptSimpleDto;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/group")
public class GroupController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    HttpServletRequest request;

    private DutyGroupService dutyGroupService;

    @Autowired
    public void setDutyGroupService(DutyGroupService dutyGroupService) {
        this.dutyGroupService = dutyGroupService;
    }

    /**
     * 获取所有值班分组信息，按排序号升序
     *
     * @return List<DutyGroupDto> 返回结果集
     * @author QcCheng Tech
     * @date 2023/8/9
     */
    @RequestMapping(value = "/all", method = {RequestMethod.GET, RequestMethod.POST})
    public List<DutyGroupDto> getAll() {
        // 从请求头中获取 token
        String token = request.getHeader(QCAuthConstant.TOKEN_HEADER_KEY);
        // 调用 platform 微服务获取有效的部门/组织信息
        List<DeptSimpleDto> projectDepts = getProjectValidDepts(token);
        //得到所有部门ID
        List<Integer> projectDeptIds = projectDepts.stream().map(DeptSimpleDto::getId).collect(Collectors.toList());

        return dutyGroupService.query(projectDeptIds, getDeptIdAndNames(projectDepts));
    }

    /**
     * 获取当前用户获取所在部门的所有值班分组信息，按排序号升序
     *
     * @return List<DutyGroupDto> 返回结果集
     * @author QcCheng Tech
     * @date 2023/8/9
     */
    @RequestMapping(value = "/dept", method = {RequestMethod.GET, RequestMethod.POST})
    public List<DutyGroupDto> getByUserDept() {
        // 从请求头中获取 token
        String token = request.getHeader(QCAuthConstant.TOKEN_HEADER_KEY);
        // 使用微服务调用获取用户有效的部门/组织信息
        List<DeptSimpleDto> validUserDepts = getUserValidDepts(token);

        //得到用户部门ID
        List<Integer> userDeptIds = validUserDepts.stream().map(DeptSimpleDto::getId).collect(Collectors.toList());

        return dutyGroupService.query(userDeptIds, getDeptIdAndNames(validUserDepts));
    }

    /**
     * 获取指定值班组
     *
     * @param id: 值班组id
     * @return DutyGroupDto
     * @author QcCheng Tech
     * @date 2023/8/9
     */
    @RequestMapping(value = "/get", method = {RequestMethod.GET})
    public DutyGroupDto getByParam(@RequestParam int id) {
        return dutyGroupService.get(id);
    }

    /**
     * 获取指定值班组
     *
     * @param id: 值班组id
     * @return DutyGroupDto
     * @author QcCheng Tech
     * @date 2023/8/9
     */
    @RequestMapping(value = "/get/{id}", method = {RequestMethod.GET})
    public DutyGroupDto getByPath(@PathVariable(required = true) int id) {
        return dutyGroupService.get(id);
    }

    /**
     * 添加值班组
     *
     * @param dto:对象
     * @return String 添加成功返回null,错误返回错误信息
     * @author QcCheng Tech
     * @date 2023/8/9
     */
    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    public String add(@RequestBody DutyGroupDto dto) {
        return dutyGroupService.add(dto);
    }

    /**
     * 修改值班组
     *
     * @param dto 值班组信息
     * @return 成功返回null
     * @author QuCheng Tech
     * @date 2023/8/9
     */
    @RequestMapping(value = "/update", method = {RequestMethod.PUT, RequestMethod.POST})
    public String update(@RequestBody DutyGroupDto dto) {
        return dutyGroupService.update(dto);
    }

    /**
     * 删除值班组
     *
     * @param id 值班组ID
     * @return 成功返回null
     * @author QcCheng Tech
     * @since 2023/5/25
     */
    @RequestMapping(value = "/delete", method = {RequestMethod.DELETE})
    public String deleteByParam(@RequestParam int id) {
        return dutyGroupService.delete(id);
    }

    /**
     * 删除
     *
     * @param id 栏目ID
     * @return 成功返回null
     * @author QcCheng Tech
     * @since 2023/5/25
     */
    @RequestMapping(value = "/delete/{id}", method = {RequestMethod.DELETE})
    public String deleteByPath(@PathVariable(required = true) int id) {
        return dutyGroupService.delete(id);
    }

    /***
     * 根据部门信息集合得到部门ID和名称对应关系
     *
     * @param depts 部门信息集合
     * @return java.util.Map<java.lang.Integer, java.lang.String>
     * @author QuCheng Tech
     * @since 2023/8/11
     */
    Map<Integer, String> getDeptIdAndNames(List<DeptSimpleDto> depts) {
        if (depts != null && depts.size() > 0x0) {
            Map<Integer, String> result = new HashMap<>();
            for (DeptSimpleDto dept : depts) {
                result.put(dept.getId(), dept.getName());
            }
            return result;
        }

        return null;
    }

    /**
     * 根据token获取用户所在项目中所有有效的部门
     *
     * @param token 用户登录得到的Token
     * @return 部门简要信息集合
     * @author QuCheng Tech
     * @since 2023/5/31
     */
    List<DeptSimpleDto> getProjectValidDepts(String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(QCAuthConstant.TOKEN_HEADER_KEY, token);

        ServiceInstance service = discoveryClient.getInstances("module-platform").get(0);
        String url = "http://" + service.getHost() + ":" + service.getPort() + "/dept/projectvalid";

        HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
        ParameterizedTypeReference<List<DeptSimpleDto>> responseType = new ParameterizedTypeReference<List<DeptSimpleDto>>() {
        };

        ResponseEntity<List<DeptSimpleDto>> response = restTemplate.exchange(
                url,//获取资源的地址
                HttpMethod.GET,
                formEntity,
                responseType
        );
        List<DeptSimpleDto> resultDto = response.getBody();
        return resultDto;
    }


    /**
     * 根据token获取用户所在的有效的部门
     *
     * @param token 用户登录得到的Token
     * @return 部门简要信息集合
     * @author QuCheng Tech
     * @since 2023/5/31
     */
    public List<DeptSimpleDto> getUserValidDepts(String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(QCAuthConstant.TOKEN_HEADER_KEY, token);

        ServiceInstance service = discoveryClient.getInstances("module-platform").get(0);
        String url = "http://" + service.getHost() + ":" + service.getPort() + "/dept/uservalid";

        HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);
        ParameterizedTypeReference<List<DeptSimpleDto>> responseType = new ParameterizedTypeReference<List<DeptSimpleDto>>() {
        };

        ResponseEntity<List<DeptSimpleDto>> response = restTemplate.exchange(
                url,//获取资源的地址
                HttpMethod.GET,
                formEntity,
                responseType
        );
        List<DeptSimpleDto> resultDto = response.getBody();

        return resultDto;
    }
}
